package controllers;

import java.io.File;
import java.security.NoSuchAlgorithmException;
import java.security.spec.InvalidKeySpecException;
import java.util.List;

import models.Seller;
import models.Store;

import org.codehaus.jackson.JsonNode;

import play.db.jpa.Transactional;
import play.libs.Json;
import play.mvc.Controller;
import play.mvc.Result;
import util.DAO;
import util.PasswordHash;
import vos.LoginCredentials;

public class SellerCtrl extends Controller {

	public static String SELLER_SESSION_KEY = "seller";

	public static Result main() {
		String suid = session(SELLER_SESSION_KEY);

		if (suid == null)
			return ok(new File("public/seller/authentication/s-auth-view.html"));

		return ok(new File("public/seller/management/s-mng-view.html"));
	}

	@Transactional(readOnly = true)
	public static Result login() throws NoSuchAlgorithmException,
			InvalidKeySpecException {
		LoginCredentials c = Json.fromJson(request().body().asJson(),
				LoginCredentials.class);
		List<Seller> res = DAO.query(Seller.class, "email", c.email);

		if (res.isEmpty()
				|| !PasswordHash.validatePassword(c.password, res.get(0)
						.getPassword()))
			return unauthorized("Usuario o contraseña incorrectos");

		try {
			session(SELLER_SESSION_KEY, res.get(0).getId().toString());
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return ok(session("seller"));
	}

	public static Result logout() {

		session().remove(SELLER_SESSION_KEY);
		return ok();
	}

	@Transactional(readOnly = true)
	public static Result myStores() throws NumberFormatException, Exception {
		// System.out.println(session(SELLER_SESSION_KEY));
		return ModelsCtrl.navigate("Seller",
				Long.parseLong(session(SELLER_SESSION_KEY)), "stores");
		// return ok();
	}

	@Transactional
	public static Result newStore() throws NumberFormatException, Exception {
		JsonNode jn = request().body().asJson();
		Store s = Json.fromJson(jn, Store.class);
		s.setOwner(new Seller(Long.parseLong(session(SELLER_SESSION_KEY))));
		DAO.persist(s);
		return ok(Json.toJson(s));

	}

}
